package com.caisejingyu.whales.home.vm

import android.arch.lifecycle.ViewModel
import android.os.CountDownTimer
import com.bumptech.glide.Glide
import com.caisejingyu.whales.common.api.ApiManager
import com.caisejingyu.whales.common.utils.DataUtil
import com.caisejingyu.whales.common.utils.FileUtil
import com.caisejingyu.whales.common.utils.RequestUtil
import com.caisejingyu.whales.common.utils.SPUtil
import com.caisejingyu.whales.control.toast.ToastUtil
import com.caisejingyu.whales.home.R
import com.caisejingyu.whales.home.api.WhalesApi
import com.caisejingyu.whales.home.common.*
import com.caisejingyu.whales.home.ui.PhotoPaymentActivity
import java.io.File
import java.lang.ref.WeakReference

/**
 * @author: xuxiaojie
 */
class PrintViewHelper(photoPaymentPreviewFragmentV2: PhotoPaymentActivity): ViewModel() {

    val api:WhalesApi = ApiManager.getInstance().getApi<WhalesApi>(WhalesApi::class.java)

    var qrCodeSuccess = false

    val countDownTimer = object: CountDownTimer(60000, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            weakV.get()?.btnCancel?.text =
                    "取消(" + (millisUntilFinished / 1000).toString() + "s)"
            if (qrCodeSuccess) {
                ThreadManager.netService.execute {
                    val response = api.wxQrcode().execute()
                    UiTask.post(Runnable {
                        weakV.get()?.let {
                            if (response.isSuccessful) {
                                // 返回上一页进行打印
                                ToastUtil.show("成功了")
                                it.setResult(Defines.INTENT_PRINT)
                                it.finish()
                                this.cancel()
                            } else {
                                // 继续重试
                                ToastUtil.show("失败了")
                            }
                        }
                    })
                }
            }
        }

        override fun onFinish() {
            weakV.get()?.finish()
        }
    }

    val weakV = WeakReference(photoPaymentPreviewFragmentV2)

    /**
     * 行为：倒计时开启
     */
    fun countDownCancelStart() {
        countDownTimer.start()
    }

    /**
     * 行为：倒计时结束
     */
    fun countDownCancelFinish() {
        countDownTimer.cancel()
    }

    /**
     * 行为：初始化微信二维码
     */
    fun initQrCode(path: String) {
        ThreadManager.netService.execute {
            // 开始显示加载中
            UiTask.post(Runnable {
                weakV.get()?.let {
                    Glide.with(it).asGif().load(R.drawable.qrcode_loading).into(it.imgQrcode)
                }
            })
            val token = RequestUtil.call(api.qiniuToken())
            token?.token?.let {
                val file = File(path)
                val key = "${DateUtil.getYear()}/${DateUtil.getMonth()}/${DateUtil.getDay()}/${SPUtil.getString(Defines.MACHINE_CODE)}_${System.currentTimeMillis()}.jpg"
                QiNiuManager.uploadManager.put(file,
                        key, it,
                        { keyUrl, info, _ ->
                            if (info?.isOK == true) {
                                ThreadManager.netService.execute {
                                    val qrcode = RequestUtil.call(api.qrcodeNow(keyUrl, path))
                                    qrcode?.codeUrl?.let {codeUrl ->
                                        // 开始显示加载中
                                        UiTask.post(Runnable {
                                            weakV.get()?.let {
                                                Glide.with(it).load("http://caijing.010hub.com/$codeUrl").into(it.imgQrcode)
                                            }
                                        })
                                    }
                                }
                            }
                        }, null)
            }
        }
    }


    /**
     * 结束生命周期时
     */
    fun onDestory() {
        weakV.clear()
    }
}